﻿using NETCONLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WIFI共享
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        //以下是移动窗口事件-------------------------------
        bool formMove = false;
        //Point p1 = new Point(); 
        int movex;
        int movey;
        int newmovex;
        int newmovey;
        int locx;
        int locy;
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            Point p2 = MousePosition;
            movex = p2.X - Location.X;
            movey = p2.Y - Location.Y;
            formMove = true;
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            formMove = false;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (formMove == true)
            {
                Point p2 = MousePosition;
                newmovex = p2.X - Location.X;
                newmovey = p2.Y - Location.Y;
                Point p3 = new Point(Location.X + newmovex - movex, Location.Y + newmovey - movey);
                this.Location = p3;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            locx = Location.X;
            locy = Location.Y;
            readMsg();
        }
        //以上是移动窗口事件-------------------------------


        //以下是窗口的关闭和最小化事件
        private void l2_Click(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Minimized;
            notifyIcon1.Visible = true;
            this.Hide();   
        }

        //从托盘还原
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;
            this.ShowInTaskbar = true;
        }


        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseWIFI();
            Application.Exit();
        }

        private void l1_Click(object sender, EventArgs e)
        {
            CloseWIFI();
            Application.Exit();
        }


        private void username_TextChanged(object sender, EventArgs e)
        {

        }

        
        private void start_or_close_Click(object sender, EventArgs e)
        {
            string use = username.Text;
            string pass = password.Text;

            if (pass.Length != 8)
            {
                MessageBox.Show("密码必须为8位！");
                return;
            }
            else if (start_or_close.Text.Equals("开启WIFI"))
            {
                startWIFI();
            }
            else 
            {
                CloseWIFI();
            }
        }

        //以下是开启WIFI函数
        public void startWIFI()
        {
            string use = username.Text;
            string pass = password.Text;
            try
            {

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口发送输入信息
                p.StandardInput.WriteLine("netsh wlan set hostednetwork mode=allow ssid=" + use + " key=" + pass);
                p.StandardInput.WriteLine("netsh wlan start hostednetwork &exit");
                p.StandardInput.AutoFlush = true;
                //p.StandardInput.WriteLine("exit");
                //向标准输入写入要执行的命令。这里使用&是批处理命令的符号，表示前面一个命令不管是否执行成功都执行后面(exit)命令，如果不执行exit命令，后面调用ReadToEnd()方法会假死
                //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令，后者表示必须前一个命令执行失败才会执行后面的命令



                //获取cmd窗口的输出信息
                string output = p.StandardOutput.ReadToEnd();

                //StreamReader reader = p.StandardOutput;
                //string line=reader.ReadLine();
                //while (!reader.EndOfStream)
                //{
                //    str += line + "  ";
                //    line = reader.ReadLine();
                //}

                p.WaitForExit();//等待程序执行完退出进程
                p.Close();


                Console.WriteLine(output);
            }
            catch
            {
                MessageBox.Show("开启失败，请检查无线网卡是否开启！");
            }
            setNet();
            saveMsg();
            username.ReadOnly = true;
            password.ReadOnly = true;
            MessageBox.Show("开启成功！");
            start_or_close.Text = "关闭WIFI";
        }

        public void CloseWIFI()
        { 
            try
            {

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口发送输入信息
                p.StandardInput.WriteLine("netsh wlan stop hostednetwork &exit");

                p.StandardInput.AutoFlush = true;
                //p.StandardInput.WriteLine("exit");
                //向标准输入写入要执行的命令。这里使用&是批处理命令的符号，表示前面一个命令不管是否执行成功都执行后面(exit)命令，如果不执行exit命令，后面调用ReadToEnd()方法会假死
                //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令，后者表示必须前一个命令执行失败才会执行后面的命令



                //获取cmd窗口的输出信息
                string output = p.StandardOutput.ReadToEnd();

                //StreamReader reader = p.StandardOutput;
                //string line=reader.ReadLine();
                //while (!reader.EndOfStream)
                //{
                //    str += line + "  ";
                //    line = reader.ReadLine();
                //}

                p.WaitForExit();//等待程序执行完退出进程
                p.Close();


                Console.WriteLine(output);
            }
            catch
            {
                MessageBox.Show("关闭失败，呵呵~");
            }
            start_or_close.Text = "开启WIFI";
            username.ReadOnly = false;
            password.ReadOnly = false;
            
        }

        
        //设置适配器
        public void setNet()
        {
            try
            {
                System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
                string connectionToShare = "本地连接"; // 被共享的网络连接
                string sharedForConnection = interfaces[0].Name; // 需要共享的网络连接

                var manager = new NETCONLib.NetSharingManager();
                var connections = manager.EnumEveryConnection;

                foreach (INetConnection c in connections)
                {
                    var props = manager.NetConnectionProps[c];
                    var sharingCfg = manager.INetSharingConfigurationForINetConnection[c];
                    if (props.Name == connectionToShare)
                    {
                        sharingCfg.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PUBLIC);
                    }
                    else if (props.Name == sharedForConnection)
                    {
                        sharingCfg.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PRIVATE);
                    }
                }
            }
            catch
            {
                MessageBox.Show("请打开网络和共享中心·查看是不是已经连接Internet！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }



        /*
         * 保存用户名密码C:\Users\Administrator\AppData\Local\shareWIFI
         */
        public void saveMsg()
        {
            if (!File.Exists("Secret.txt"))
            {
                FileStream fs1 = new FileStream("Secret.txt", FileMode.Create, FileAccess.Write);//创建写入文件 
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(this.username.Text.Trim() + "\r\n" + this.password.Text);//开始写入值
                sw.Close();
                fs1.Close();
            } 
            else
            {
                FileStream fs = new FileStream("Secret.txt", FileMode.Open, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(this.username.Text.Trim() + "\r\n" + this.password.Text);//开始写入值
                sr.Close();
                fs.Close();

            }
        }

        public void readMsg()
        {
            if (File.Exists("Secret.txt"))
            {
                StreamReader sr = new StreamReader("Secret.txt", Encoding.Default);
                String line;
                line = sr.ReadLine();
                username.Text = line;
                line = sr.ReadLine();
                password.Text = line;
                sr.Close();
            }
            
        }


    }


}
